#include <assert.h>
#include <jni.h>
#include <string.h>

#include <android/sensor.h>
#include <android/log.h>
#include <android/looper.h>

#define TAG "YwuPocket"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)

#define LOOPER_ID 1

int lightSensorCallback(int fd, int events, void* data) {
    LOGD("xxxxxxxxxxxxxxxxxxxxxxxxxx lightSensorCallback fd=%d events=%d\n", fd, events);
}

void Java_ywu_pocket_PocketModeService_startMonitoring(JNIEnv* env, jclass clazz) {
    ASensorManager* sensorManager = ASensorManager_getInstance();
    assert(sensorManager);

    ALooper* looper = ALooper_forThread();
    if(looper == NULL)
        looper = ALooper_prepare(ALOOPER_PREPARE_ALLOW_NON_CALLBACKS);

    ASensorRef lightSensor = ASensorManager_getDefaultSensor(sensorManager, ASENSOR_TYPE_LIGHT);
    assert(lightSensor);
    LOGI("lightSensor: %s, vendor: %s", ASensor_getName(lightSensor), ASensor_getVendor(lightSensor));

    ASensorEventQueue* queue = ASensorManager_createEventQueue(sensorManager, looper, LOOPER_ID, NULL, NULL);
    assert(queue);
    LOGD("xxxxxxxxxx %s", queue);
    ASensorEventQueue_enableSensor(queue, lightSensor);
    ASensorEventQueue_setEventRate(queue, lightSensor, 1000L/60); 
    LOGD("xxxxxxxxxx ASensorEventQueue_setEventRate --------");

    int ident;
    int events;
    while (1) {
        LOGD("xxxxxxxxxx while(1)");
        while ((ident=ALooper_pollAll(-1, NULL, &events, NULL) >= 0)) {
            LOGD("xxxxxx looper_poll ident=%d, events=%d", ident, events);
            // If a sensor has data, process it now.
            if (ident == LOOPER_ID) {
                ASensorEvent event;
                while (ASensorEventQueue_getEvents(queue, &event, 1) > 0) {
                    LOGI("xxxxxxxxx light = %f lux", event.light);
                }
            }
        }
        LOGI("XXXX xxxxx done");
    }

}
